package com.waimai1.waimai.filter;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.Claim;
import com.waimai1.waimai.common.BaseContext;
import com.waimai1.waimai.common.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;
import com.waimai1.waimai.common.R;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.logging.LogRecord;
@Slf4j
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
//    路径匹配器，支持通配符
    @Autowired
    private JWTUtil jwtUtil;
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //取出请求头中的acid保存备用
        log.info("acid:"+request.getHeader("acid"));
        int acid=(null!=request.getHeader("acid"))?Integer.parseInt(request.getHeader("acid")):0;
        BaseContext.setAcid(acid);
//        1、获取本次请求的URI
        String requestURI = request.getRequestURI();// /backend/index.html

        log.info("拦截到请求：{}",requestURI);

//        定义不需要处理的请求路径
        String[] urls = new String[]{
                "/user/login",
                "/user/logout",
                "/img/**",
                "/static/**",
                "/movie/get*",
               "/pinpai/pinpai/*",
                "/order/hwNotify",
                "/wepay/notify",
                "/wepay/partnerNotify",
                "/wepay/refundNotify",
                "/pinpai/get*",
                "/local/upload",
                "/manage/login",
                "/order/hwSearchOrder",
                "/localshop/get**/**",
                "/zhanshi/get**/**",
                "/manage/shopLogin",
                "/mahua/**",
                "/pageComponent/**",
                "/fl/notify"

        };
//        2、判断本次请求是否需要处理
        boolean check = check(urls, requestURI);
//        3、如果不需要处理，则直接放行
        if(check){
            log.info("本次请求{}不需要处理",requestURI);
            filterChain.doFilter(request,response);
            return;
        }
//        4-1、判断登录状态，如果已登录，解析takon，把id存入线程变量，放行
        String token=request.getHeader("Authorization");
        Map<String, Claim> retoken=jwtUtil.verifyToken(token);
//        retoken.entrySet().stream().forEach(item->{
//            log.info("retoken:{}--{}",item.getKey(),item.getValue().asString());
//        });
//        log.info("retoken PC_openId:{}",retoken.get("PC_openId").asString());
        if(null!=retoken){
            //小程序登录
            if(null!=retoken.get("openid")){
                log.info("小程序登录");
                String id = retoken.get("openid").asString();
                String phone = retoken.get("phone").asString();
                BaseContext.setopenId(id);
                BaseContext.setPhone(phone);
            }
            //后台管理网页 管理员登录
            if(null!=retoken.get("role")){
                log.info("管理员登录");
                String role = retoken.get("role").asString();
                String name = retoken.get("name").asString();
                BaseContext.setRole(role);
                BaseContext.setName(name);
            }
            //后台管理网页 商户登录
            if(null!=retoken.get("PC_openId")){
                String id = retoken.get("PC_openId").asString();
                log.info("商户登录 setopenId:{}",id);
                BaseContext.setopenId(id);
            }
            filterChain.doFilter(request,response);
            return;
        }
//        5、如果未登录或token无效则返回未登录结果，通过输出流方式向客户端页面响应数据
        response.getWriter().write(JSON.toJSONString(R.err(903,"NOTLOGIN")));

    }
    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls 规则
     * @param requestURI 入参
     * @return true
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
